package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"time"
)

var Logger *zap.Logger

type _zap struct{}

// CustomEncodeLevel 自定义日志级别显示
func customEncodeLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString("[" + level.CapitalString() + "]")
}

// CustomEncodeTime 自定义时间格式显示
func customEncodeTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString("[" + t.Format("2006-01-02 15:04:05.000") + "]")
}

// CustomEncodeCaller 自定义行号显示
func customEncodeCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString("[" + caller.TrimmedPath() + "]")
}

// getEncoderConfig 获取zapcore.EncoderConfig
func (z *_zap) getEncoderConfig() zapcore.EncoderConfig {
	return zapcore.EncoderConfig{
		// 设置编码为 JSON 时的KEY
		MessageKey:    "message",
		LevelKey:      "level",
		TimeKey:       "time",
		NameKey:       "logger",
		CallerKey:     "caller",
		FunctionKey:   "func", // 是否打印函数名
		StacktraceKey: "stacktrace",
		// 配置换行符
		SkipLineEnding: false,                     // 是否跳过添加换行符, false 为跳过添加换行符
		LineEnding:     zapcore.DefaultLineEnding, // 默认换行符\n
		// Encode配置
		EncodeLevel:    customEncodeLevel,
		EncodeTime:     customEncodeTime,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   customEncodeCaller,
	}
}

// getZapCore 获取zapcore.Core
func (z *_zap) getZapCore(verbose bool) zapcore.Core {
	encoder := zapcore.NewConsoleEncoder(z.getEncoderConfig())
	var level zapcore.Level
	if verbose {
		level = zap.DebugLevel
	} else {
		level = zap.InfoLevel
	}
	return zapcore.NewTee(
		zapcore.NewCore(encoder, zapcore.Lock(os.Stdout), level),
	)

}

// Init 初始化zap日志库
func Init(verbose bool) {
	var z = new(_zap)
	core := z.getZapCore(verbose)
	Logger = zap.New(zapcore.NewTee(core), zap.AddCaller())
	zap.ReplaceGlobals(Logger) // 替换zap全局logger
	zap.L().Info("init logger success")
	return
}
